// 百度云语音识别工具类
class BaiduSpeechRecognition {
  constructor(config) {
    this.config = config;
  }

  // 获取百度云访问令牌
  async getAccessToken() {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://aip.baidubce.com/oauth/2.0/token',
        method: 'POST',
        data: {
          grant_type: 'client_credentials',
          client_id: this.config.apiKey,
          client_secret: this.config.secretKey
        },
        success: (res) => {
          if (res.data && res.data.access_token) {
            resolve(res.data.access_token);
          } else {
            reject(new Error('获取访问令牌失败'));
          }
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }

  // 语音识别
  async recognize(audioFilePath) {
    try {
      const token = await this.getAccessToken();
      
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: `https://vop.baidu.com/server_api`,
          filePath: audioFilePath,
          name: 'audio',
          formData: {
            format: this.config.format,
            rate: this.config.sampleRate,
            channel: 1,
            cuid: this.config.appId,
            token: token,
            dev_pid: 1537 // 普通话(支持简单的英文识别)
          },
          success: (res) => {
            try {
              const result = JSON.parse(res.data);
              if (result.err_no === 0 && result.result && result.result.length > 0) {
                resolve({
                  success: true,
                  text: result.result[0],
                  confidence: result.result.length > 1 ? result.result[1] : null
                });
              } else {
                reject(new Error(result.err_msg || '识别失败'));
              }
            } catch (parseError) {
              reject(new Error('解析识别结果失败'));
            }
          },
          fail: (error) => {
            reject(error);
          }
        });
      });
    } catch (error) {
      throw new Error(`语音识别失败: ${error.message}`);
    }
  }
}

module.exports = BaiduSpeechRecognition;